<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\OpenShop\InvestmentPromotion\ShopManualEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserBaseInfoEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Library\Rms\RmsUserApi;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopProcessDetailModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopShopManual;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationCustomerAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationHouseEvaluateModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationProductAnalysisModel;
use App\Models\OpenShop\SiteLocation\SiteLocationAgainAssemble;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\FeishuMini\ConsultantsService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\PlaceHolderSiteLocationService;
use App\Service\OpenShop\SiteLocation\SiteLocationAuditService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Service\WorkOrder\Web\ApplyService;
use App\Support\ChangeSupport;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Kuafu\File\FileUtil;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class SelectionService extends BaseService
{
    public string $orderNo;

    public function __construct(string $orderNo = '')
    {
        $this->orderNo = $orderNo;
    }

    /**
     * 重新选址
     *
     * @param int $changeType
     * @param string $changeReason
     * @return bool
     * @throws GuzzleException
     */
    public function reSelection(
        int $changeType,
        string $changeReason,
        array $selectLocation,
        string $addressPrefix,
        int $developManagerId
    ): bool {
        $openShopSiteLocationModel = OpenShopSiteLocationModel::query()
                                                              ->whereIn('source',
                                                                  [
                                                                      OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                                      OpenShopSiteLocationModel::SOURCE_HOUSING
                                                                  ])->with(['signOrderRel', 'mainProcessRel'])
                                                              ->where('orderNo', $this->orderNo)->first();

        $changeReasonText = '';
        switch ($changeType) {
            case SiteLocationEnum::SELECTION_CHANGE_TYPE_1:
                $openShopSiteLocationModel->siteStatus = OpenShopSiteLocationModel::SITE_STATUS_3;
                $openShopSiteLocationModel->save();
                OpenShopSiteLocationExamineLogModel::query()->where('orderNo', $this->orderNo)
                                                   ->update(['isDeleted' => 1]);
                $siteLocationServer = new SiteLocationAuditService();
                $siteLocationServer->setOrderNo($this->orderNo);
                $siteLocationServer->setRmsUserId((int)getRmsUserInfoByAuth()->id);
                $siteLocationServer->setSiteLocationMode($openShopSiteLocationModel);

                $siteLocation = OpenShopSiteLocationModel::query()->whereIn('source',
                    [
                        OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                        OpenShopSiteLocationModel::SOURCE_HOUSING
                    ])->where('orderNo', $this->orderNo)->first();
                if ($siteLocation->bindId == 0) {
                    $siteLocation->clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_0;
                } else {
                    $siteLocation->clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_10;
                }
                $siteLocation->save();

                $changeReasonText = '【仅数据调整】' . $changeReason;
                $siteLocationServer->handleSourceFromOpenShop($this->orderNo, SiteLocationEnum::STATUS_2
                    , $changeReasonText,
                    (int)getRmsUserInfoByAuth()->id, getRmsUserInfoByAuth()->username);
                break;
            case SiteLocationEnum::SELECTION_CHANGE_TYPE_2:
                // 获取开发顾问
                $developConsultantId = $openShopSiteLocationModel->developConsultantId ?? 0;
                // 判断是否选址已经离职
//                $userInfo = current((new RmsUserApi())->getFsUsers('', ['rmsUserId', 'isExited'], '',
//                    $developConsultantId)['data']['lists'] ?? []);
                $isExited = KmsUser::query()
                                   ->where('rmsUserId', $developConsultantId)
                                   ->where('isExited', KmsUser::IS_EXITED_OFF)
                                   ->count();
                if ($isExited >= 1) {
                    // 未离职
                    $stepStatus            = MissionTemplateEnum::STEP_STATUS_4;
                    $openShopLocationModel = MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER;
                    $isDeleted             = [
                        'isDeleted' => 0
                    ];
                } else {
                    // 已经离职
                    $stepStatus            = MissionTemplateEnum::STEP_STATUS_3;
                    $openShopLocationModel = MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER_STAY;
                    $isDeleted             = [
                        'isDeleted' => 1
                    ];
                }

                $changeReasonText = '【重新选址】' . $changeReason;

                // 判断是新老选址
                $bindId = $openShopSiteLocationModel->bindId;
                if (!empty($openShopSiteLocationModel->bindId)) {

                    //换绑操作  修复已占房源信息
                    OpenShopSiteLocationModel::query()
                                             ->where('id', $openShopSiteLocationModel->id)
                                             ->whereIn('source',
                                                 [
                                                     OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                     OpenShopSiteLocationModel::SOURCE_HOUSING
                                                 ])
                                             ->withoutGlobalScope('isDel')
                                             ->update(array_merge([
                                                 'bindId'     => OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE,
                                                 'orderNo'    => 'FY' . $openShopSiteLocationModel->id,
                                                 'source'     => OpenShopSiteLocationModel::SOURCE_HOUSING,
                                                 'clueStatus' => OpenShopSiteLocationModel::CLUE_STATUS_5,
                                             ], $isDeleted));

                    OpenShopSiteLocationCustomerAnalysisModel::query()
                                                             ->where('siteId', $openShopSiteLocationModel->id)
                                                             ->update([
                                                                 'orderNo'   => 'FY' . $openShopSiteLocationModel->id,
                                                                 'updatedAt' => time(),
                                                             ]);

                    OpenShopSiteLocationProductAnalysisModel::query()
                                                            ->where('siteId', $openShopSiteLocationModel->id)
                                                            ->update([
                                                                'orderNo'   => 'FY' . $openShopSiteLocationModel->id,
                                                                'updatedAt' => time(),
                                                            ]);

                    OpenShopUploadFileResourceModel::query()
                                                   ->where('orderNo', $openShopSiteLocationModel->orderNo)
                                                   ->update([
                                                       'orderNo'   => 'FY' . $openShopSiteLocationModel->id,
                                                       'updatedAt' => time(),
                                                   ]);

                    OpenShopSiteLocationHouseEvaluateModel::query()
                                                          ->where('orderNo', $openShopSiteLocationModel->orderNo)
                                                          ->update([
                                                              'orderNo'   => 'FY' . $openShopSiteLocationModel->id,
                                                              'updatedAt' => time(),
                                                          ]);

                    OpenShopSiteLocationExamineLogModel::query()
                                                       ->withoutGlobalScope('isDel')
                                                       ->where('orderNo', $openShopSiteLocationModel->orderNo)
                                                       ->update([
                                                           'orderNo'   => 'FY' . $openShopSiteLocationModel->id,
                                                           'updatedAt' => time(),
//                                                           'status'    => OpenShopSiteLocationExamineLogModel::STATUS_REFUSE
                                                       ]);

                    OpenShopSiteLocationExamineLogModel::query()
                                                       ->where('orderNo', $openShopSiteLocationModel->orderNo)
                                                       ->insert([
                                                           'orderNo'      => 'FY' . $openShopSiteLocationModel->id,
                                                           'source'       => 1,
                                                           'position'     => 0,
                                                           'isToStore'    => 0,
                                                           'content'      => $changeReasonText,
                                                           'status'       => OpenShopSiteLocationExamineLogModel::STATUS_REFUSE,
                                                           'createdAt'    => time(),
                                                           'createdByUid' => (int)getRmsUserInfoByAuth()->id,
                                                           'updatedAt'    => time(),
                                                           'updatedByUid' => (int)getRmsUserInfoByAuth()->id,
                                                           'isDeleted'    => 0
                                                       ]);
                }

                OpenShopSiteLocationExamineLogModel::query()->where('source', 0)
                                                   ->where('orderNo', $openShopSiteLocationModel->orderNo)
                                                   ->delete();

                $xzOpenShopSiteLocationModel = OpenShopSiteLocationModel::query()
                                                                        ->with('signOrderRel')->whereIn('source',
                        [
                            OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                            OpenShopSiteLocationModel::SOURCE_HOUSING
                        ])
                                                                        ->withoutGlobalScope('isDel')
                                                                        ->where('id', $bindId)
                                                                        ->first();

                if (!empty($xzOpenShopSiteLocationModel)) {
                    $xzOpenShopSiteLocationModel->isDeleted  = 0;
                    $xzOpenShopSiteLocationModel->siteStatus = 0;
                    $xzOpenShopSiteLocationModel->clueStatus = 0;
                    $xzOpenShopSiteLocationModel->save();
                }

                OpenShopSiteMissionModel::query()
                                        ->where('orderNo', $this->orderNo)
                                        ->where('stepStatus', '>', $stepStatus)
                                        ->update(['isDeleted' => OpenShopOrderManagerModel::DELETED]);

                $dealUid = (new MissionTemplateService)->getNextHandlerId($this->orderNo, $stepStatus);
                OpenShopSiteMissionModel::query()
                                        ->where('orderNo', $this->orderNo)
                                        ->where('stepStatus', $stepStatus)
                                        ->update(['status' => SiteMissionEnum::STATUS_1, 'dealUid' => $dealUid]);

                OpenShopMainProcessModel::query()->where('orderNo', $this->orderNo)->update([
                    'nowStepStatus' => $stepStatus,
                    'step'          => MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION,
                ]);

                OpenShopLocationModel::query()->where('orderNo', $this->orderNo)->update([
                    'step' => $openShopLocationModel,
                ]);

                OrderService::updateOrderPermissionAnchor($this->orderNo);

                OpenShopSiteLocationModel::query()
                                         ->where('id', $openShopSiteLocationModel->id)
                                         ->whereIn('source',
                                             [
                                                 OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                 OpenShopSiteLocationModel::SOURCE_HOUSING
                                             ])
                                         ->update([
                                             'siteStatus' => 0,
                                         ]);

                // 回退任务
                $engineeringConstructionOrder = OpenShopEngineeringConstructionModel::query()
                                                                                    ->where("orderNo", $this->orderNo)
                                                                                    ->first();

                if ($engineeringConstructionOrder) {
                    $engineeringConstructionOrder->step = MainProcessEnum::ENGINEER_CONSTRUCT_STAY;
                    $engineeringConstructionOrder->save();
                }

                // 把门店名称改回xxx的店
                $mainProcess = OpenShopMainProcessModel::query()->where('orderNo', $this->orderNo)->first();
                $username    = (string)optional($mainProcess->userIdentityCardRel)->name;
                $shopName    = $username . '的店';
                ShopService::updateShopName($this->orderNo, $shopName);

                $signTime           = 0;
                $confirmTime        = 0;
                $historyConfirmTime = [];
                OpenShopProcessDetailModel::query()
                                          ->where('mainProcessId', $mainProcess->id)
                                          ->whereIn('mainProcessType', [
                                              MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN,
                                              MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION
                                          ])
                                          ->whereIn('processType', [
                                              MainProcessEnum::INVESTMENT_SIGN_CONTRACT_SIGNED,
                                              MainProcessEnum::SHOP_LOCATION_CONFIRM
                                          ])
                                          ->each(function (OpenShopProcessDetailModel $openShopProcessDetailModel) use (
                                              &$signTime,
                                              &$confirmTime,
                                              &$historyConfirmTime
                                          ) {
                                              if ($openShopProcessDetailModel->mainProcessType == MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN && $openShopProcessDetailModel->processType == MainProcessEnum::INVESTMENT_SIGN_CONTRACT_SIGNED) {
                                                  $signTime = $openShopProcessDetailModel->createdAt->timestamp;
                                              }
                                              if ($openShopProcessDetailModel->mainProcessType == MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION && $openShopProcessDetailModel->processType == MainProcessEnum::SHOP_LOCATION_CONFIRM) {
                                                  $historyConfirmTime[] = $openShopProcessDetailModel->createdAt->timestamp;
                                                  $confirmTime          = $openShopProcessDetailModel->createdAt->timestamp;
                                              }
                                          });

                $areaPrefix = explode('-', $openShopSiteLocationModel->cityArea);
                //添加重新选址统计数据
                $againAssemble                     = SiteLocationAgainAssemble::query()->firstOrCreate([
                    'shopCode' => (int)optional($openShopSiteLocationModel->signOrderRel)->shopCode
                ]);
                $againAssemble->developerName      = KmsUser::query()->where('rmsUserId', $developManagerId)
                                                            ->value('name');
                $againAssemble->developerId        = $developManagerId;
                $againAssemble->orderNo            = $this->orderNo;
                $againAssemble->signTime           = $signTime;
                $againAssemble->contractTime       = $openShopSiteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 ? $openShopSiteLocationModel->ctSubmitTime : 0;
                $againAssemble->confirmTime        = $confirmTime;
                $againAssemble->historyConfirmTime = implode(',', $historyConfirmTime);
                $againAssemble->againTime          = time();
                $againAssemble->province           = $areaPrefix[0] ?? '';
                $againAssemble->city               = $areaPrefix[1] ?? '';
                $againAssemble->district           = $areaPrefix[2] ?? '';
                $againAssemble->address            = $openShopSiteLocationModel->address;
                $againAssemble->desc               = $changeReason;
                $againAssemble->save();

                break;
            case SiteLocationEnum::SELECTION_CHANGE_TYPE_3:
                // 判断是否可以迁址
                $mainInfo     = OpenShopMainProcessModel::query()->where('orderNo', $this->orderNo)->first();
                $locationList = OpenShopMainProcessModel::query()
                                                        ->where('childLocationOrder', MainProcessEnum::CHILD_ORDER_1)
                                                        ->where('locationPid', $mainInfo->id)
                                                        ->where('step', '!=',
                                                            MainProcessEnum::MAIN_PROCESS_START_BUSINESS)
                                                        ->with([
                                                            'signOrderRel'
                                                        ])
                                                        ->get()
                                                        ->filter(function ($item) {
                                                            return (!empty($item->signOrderRel) && $item->signOrderRel->status != SignOrderEnum::ORDER_STATUS_NO);
                                                        });
                if ($locationList->count() > 0) {
                    throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NOT_ALLOW_LOCATION_MANY));
                }
                $shopId = (int)optional($openShopSiteLocationModel->mainProcessRel)->shopId;
                // 解绑功能开通
                ApplyService::resetFunctionOpen(
                    $shopId, [
                    OrderEnum::PROBLEM_PID_5_CHILDREN_101,
                    OrderEnum::PROBLEM_PID_5_CHILDREN_102,
                    OrderEnum::PROBLEM_PID_5_CHILDREN_103,
                    OrderEnum::PROBLEM_PID_5_CHILDREN_104,
                    OrderEnum::PROBLEM_PID_5_CHILDREN_105,
                ], 0, (int)getRmsUserInfoByAuth()->id, getRmsUserInfoByAuth()->username, 1
                );
                /*
                //修改功能开通状态
                WorkOrderApplyMainModel::query()
                                       ->where('problemPid', OrderEnum::PROBLEM_PID_5)
                                       ->whereIn('problemChildId', [
                                           OrderEnum::PROBLEM_PID_5_CHILDREN_101,
                                           OrderEnum::PROBLEM_PID_5_CHILDREN_102,
                                           OrderEnum::PROBLEM_PID_5_CHILDREN_103,
                                           OrderEnum::PROBLEM_PID_5_CHILDREN_104
                                       ])
                                       ->where('shopId', $shopId)
                                       ->update([
                                           'status'       => OrderEnum::MAIN_STATUS_ING,
                                           'step'         => MissionEnum::STEP_1,
                                           'completeTime' => 0,
                                       ]);*/

                $changeReasonText = '【迁址】' . $changeReason;
                (new OrderService())->copyNewOrder($this->orderNo);

                // 迁址更新门店属性(迁址状态更改为是)
                RmsShopRemote::updateShopAttribute($shopId, ['relocationStatus' => 1]);
                break;
            case SiteLocationEnum::SELECTION_CHANGE_TYPE_LOCATION:
                // 更改选址范围
                OpenShopUserBaseInfoModel::query()->where('orderNo', $this->orderNo)->update([
                    'chooseShopProvinceCode'  => $selectLocation['province'],
                    'chooseShopCityCode'      => $selectLocation['city'],
                    'chooseShopDistrictCode'  => $selectLocation['district'],
                    'chooseShopAddressPrefix' => $addressPrefix,
                ]);

                $updateData = [
                    'provinceCode'           => $selectLocation['province'],
                    'chooseShopProvinceCode' => $selectLocation['province'],
                    'cityCode'               => $selectLocation['city'],
                    'areaCode'               => $selectLocation['district'],
                    'cityArea'               => $addressPrefix,
                    'address'                => $addressPrefix,
                ];
                // 更改开发经理
                if ($developManagerId) {
                    // 通过 userid 获取 rms 用户信息
                    $operateUser                         = RmsUserService::getRmsUserInfoByUserIds([$developManagerId],
                        [],
                        true)['data'][0] ?? [];
                    $operateUserName                     = $operateUser['username'] ?? '';
                    $updateData['developConsultantId']   = $developManagerId;
                    $updateData['developConsultantName'] = $operateUserName;
                }
                OpenShopSiteLocationModel::query()->where('orderNo', $this->orderNo)->update($updateData);
                $missionInfo = OpenShopSiteMissionModel::query()
                                                       ->where('orderNo', $this->orderNo)
                                                       ->where('status', SiteMissionEnum::STATUS_1)
                                                       ->whereIn('stepStatus', [
                                                           MissionTemplateEnum::STEP_STATUS_4,
                                                           MissionTemplateEnum::STEP_STATUS_3
                                                       ])
                                                       ->first();
                // 获取省总信息
                $provinceCode = OpenShopSignOrderPermissionAnchorModel::query()
                                                                      ->where('orderNo', $this->orderNo)
                                                                      ->first();

                // 刷新权限
                $changeReasonText = '【选址范围调整】' . $changeReason;
                OrderService::updateOrderPermissionAnchor($this->orderNo);

                if (!empty($missionInfo)) {
                    switch ($missionInfo->stepStatus) {
                        case  MissionTemplateEnum::STEP_STATUS_3:
                            $manager              = OrganizationManageService::getOrganizationInfoByProvinceCodeCode(
                                $provinceCode->provinceCode, $provinceCode->cityCode, 1
                            );
                            $missionInfo->dealUid = $manager->operationUid;
                            $missionInfo->save();
                            break;
                    }

                }
            default;
        }

        $orderLog = new OpenShopSignOrderLogModel();

        $orderLog->orderId      = $openShopSiteLocationModel->signOrderRel->id ?? 0;
        $orderLog->content      = OpenShopSignOrderLogModel::TYPES[OpenShopSignOrderLogModel::INVALID_ORDER_RE_SITE];
        $orderLog->type         = OpenShopSignOrderLogModel::INVALID_ORDER_RE_SITE;
        $orderLog->createdByUid = getRmsUserInfoByAuth()->id;
        $orderLog->operatorName = getRmsUserInfoByAuth()->username;
        $orderLog->updatedByUid = getRmsUserInfoByAuth()->id;

        $orderLog->changes = json_encode([
            [
                "theme"      => "选址变更",
                "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
                "data"       => [
                    [
                        "key"         => "text",
                        "beforeValue" => '',
                        "afterValue"  => '',
                        "beforeText"  => '-',
                        "afterText"   => $changeReasonText,
                        "type"        => ChangeSupport::FILED_TYPE_STRING,
                        "description" => "选址变更"
                    ]
                ]
            ]
        ], JSON_UNESCAPED_UNICODE);

        $orderLog->save();

        return true;
    }

    /**
     * @param string $username
     * @return array
     * @throws GuzzleException
     */
    public static function getManagerList(string $username = ""): array
    {
        $userData = RmsUserRemote::getManagerList($username) ?? [];
//        $userData    = RmsUserService::getWebUserList();
        $managerList = [];
        foreach ($userData as $item) {
            $managerList[] = [
                'id'   => $item['id'],
                'name' => $item['username'],
            ];
        }
        return $managerList;
    }

    /**
     * @param string $username
     * @return array
     * @throws GuzzleException
     */
    public static function getSiteTaskHandlerList(string $username = ""): array
    {
        $userData = RmsUserRemote::getSiteTaskHandlerList($username) ?? [];
//        $userData    = RmsUserService::getWebUserList();
        $managerList = [];
        foreach ($userData as $item) {
            $managerList[] = [
                'id'   => $item['id'],
                'name' => $item['username'],
            ];
        }
        return $managerList;
    }

    public static function managerDetail(string $orderNo, int $type): array
    {
        $mainProcessId = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->value('id');
        if (!$mainProcessId) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_NO_NULL));
        }

        $manager = OpenShopOrderManagerModel::query()
                                            ->where('mainProcessId', $mainProcessId)
                                            ->where('type', $type)
                                            ->first();
        if (!$manager) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_NO_DEVELOP_MANAGER));
        }
        $placeholder = new PlaceHolderSiteLocationService($orderNo);

        return [
            'id'              => $manager->managerUid,
            'name'            => $manager->managerName,
            'managerType'     => $type,
            'managerTypeText' => OpenShopOrderManagerModel::TYPE_MAP[$type] ?? '',
            'placeholder'     => empty($placeholder->getPlaceholderInfo()) ? null :
                PlaceHolderSiteLocationResource::collection([$placeholder->getPlaceholderInfo()])
                                               ->getIterator()->current(),
        ];
    }

    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function addManager($orderNo, $managerId, $rmsInfo)
    {
        $shopLocation = OpenShopLocationModel::query()->where("orderNo", $orderNo)->first();
        if (empty($shopLocation)) {
            throw new ResponseHttpException(BaseErrorCode::$SHOP_LOCATION_NOT_EXISTS);
        }

        $rmsUid = ($rmsInfo->id) ?? 0;
        //主流程表
        $orderModel    = OpenShopSignOrderModel::query()
                                               ->where('orderNo', $orderNo)
                                               ->first();
        $mainProcessId = $orderModel->mainProcessId;
        //开发经理名称
        $managerName                    = RmsUserService::getRmsUserInfoByUserIds([$managerId])['data'][0]['username'] ?? '';
        $mainProcessModel               = OpenShopMainProcessModel::find($mainProcessId);
        $mainProcessModel->step         = MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION;
        $mainProcessModel->updatedByUid = $rmsUid;
        $mainProcessModel->save();

        //获取订单基础信息
        $userBaseInfoObj = OpenShopUserBaseInfoModel::getDataByOrderNo($orderNo);
        //获取筹备uid
        $manager = OrganizationManageService::getOrganizationInfoByType(OrganizationManageEnum::TYPE_BRANCH_OFFICE,
            $userBaseInfoObj->chooseShopProvinceCode);

        if ($manager && $manager["preparationUid"] > 0) {
            //经理表写入筹备数据
            OpenShopOrderManagerModel::generateManagerOrUpdate(
                OpenShopOrderManagerModel::MANAGER_TYPE_4,
                $mainProcessId,
                $manager["preparationUid"],
                $manager["preparationName"]
            );
        }

        //空间设计表写入
        OpenShopSpaceDesignModel::query()->insert([
            "mainProcessId"   => $mainProcessId,
            "orderNo"         => $orderNo,
            "createdAt"       => time(),
            "preparationUid"  => $manager["preparationUid"] ?? 0,
            "preparationName" => $manager["preparationName"] ?? ""
        ]);

        //流程日志表
        $mainProcessId = $mainProcessModel->id;
        OpenShopLocationModel::query()
                             ->where("orderNo", $orderNo)
                             ->update([
                                 'step'                  => MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER,
                                 'investmentManagerId'   => $managerId,
                                 'investmentManagerName' => $managerName,
                                 'assignTime'            => time(),
                                 'updatedByUid'          => $rmsUid
                             ]);

        OpenShopOrderManagerModel::generateManagerOrUpdate(
            OpenShopOrderManagerModel::MANAGER_TYPE_2,
            $mainProcessId,
            $managerId,
            $managerName
        );


        //选址增加空记录
        OpenShopSiteLocationModel::shopLocationManagerInitOrUpdate($orderNo, $managerName, $managerId, $mainProcessId,
            $managerId);

        //判断是否存在自带址以及房源编号
        $signOrderModel = OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->first();
        if (
            $signOrderModel->baseInfoRel->isSelfWithAddress == UserBaseInfoEnum::SELF_WITH_ADDRESS
            &&
            !empty($clueNo = $signOrderModel->baseInfoRel->clueNo)
        ) {
            try {
                $siteLocationClueModel = OpenShopSiteLocationModel::query()
                                                                  ->where("orderNo", $clueNo)
                                                                  ->whereIn('source',
                                                                      [
                                                                          OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                                          OpenShopSiteLocationModel::SOURCE_HOUSING
                                                                      ])
                                                                  ->first();
                $siteLocationModel     = OpenShopSiteLocationModel::query()
                                                                  ->whereIn('source',
                                                                      [
                                                                          OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                                                                          OpenShopSiteLocationModel::SOURCE_HOUSING
                                                                      ])->where("orderNo", $orderNo)
                                                                  ->first();

                if ($siteLocationModel && $siteLocationClueModel && $siteLocationClueModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                    SiteLocationService::choosesClue($siteLocationModel->id, $siteLocationClueModel->id);
                    $pid            = OpenShopMainProcessModel::query()->where("orderNo", $orderNo)->first()->pid;
                    $shopOrderCount = OpenShopMainProcessModel::query()->where("pid", $pid)->count();
                    if ($shopOrderCount > 1) {
                        $signOrderModel->baseInfoRel->clueNo = "";
                        $signOrderModel->baseInfoRel->save();
                    }
                } else {
                    throw new Exception("房源或选址信息获取失败");
                }
            } catch (Exception $exception) {
                logException(
                    "指派开发经理完成 - 自带址绑定失败",
                    $exception,
                    [
                        "orderNo"        => $orderNo,
                        "siteLocationId" => $siteLocationModel ? $siteLocationModel->id : 0,
                        "clueId"         => $siteLocationClueModel ? $siteLocationClueModel->id : 0
                    ],
                    true,
                    true
                );
            }
        }

        event(new SignSiteMissionEvent($orderNo, MissionTemplateEnum::STEP_STATUS_3, $rmsUid));
        event(new OpenShopProcessEvent($rmsUid, $mainProcessId, MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION,
            MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER));
        /*
        // 产品说先不记录
        $orderLog = new OpenShopSignOrderLogModel();
        $orderLog->orderId = $orderModel->id;
        $orderLog->content = OpenShopSignOrderLogModel::TYPES[OpenShopSignOrderLogModel::SELECTION_DEVELOP_MANAGER];
        $orderLog->type    = OpenShopSignOrderLogModel::SELECTION_DEVELOP_MANAGER;
        $orderLog->operatorName    = $rmsInfo->username;
        $orderLog->createdByUid    = $rmsInfo->id;
        $orderLog->updatedByUid    = $rmsInfo->id;
        $orderLog->save();
        */
    }

    public static function addReport(
        $reqData,
        $rmsInfo,
        $mapping
    ) {
        try {
            DB::beginTransaction();
            $rmsUid = ($rmsInfo->id) ?? 0;
            //主流程表
            //根据orderNo获取主流程ID
            $orderModel                     = OpenShopSignOrderModel::query()
                                                                    ->where('orderNo', $reqData['orderNo'])
                                                                    ->first();
            $mainProcessId                  = $orderModel->mainProcessId;
            $mainProcessModel               = OpenShopMainProcessModel::find($mainProcessId);
            $mainProcessModel->step         = MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION;
            $mainProcessModel->updatedByUid = $rmsUid;
            $mainProcessModel->save();
            //流程日志表
            $mainProcessId = $mainProcessModel->id;
            $locationModel = OpenShopLocationModel::firstOrNew([
                'orderNo' => $reqData['orderNo'],
            ]);
            self::insertReport($reqData, $rmsUid, $mainProcessId, $locationModel,
                MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT);
            //增加收银方式mapping
            $mappingData = [];
            foreach ($mapping as $key => $value) {
                $mappingData[$key]['orderNo']      = $reqData['orderNo'];
                $mappingData[$key]['url']          = getPrivateFileKey($value);
                $mappingData[$key]['createdAt']    = time();
                $mappingData[$key]['createdByUid'] = $rmsInfo->id;
                $mappingData[$key]['updatedAt']    = time();
                $mappingData[$key]['type']         = OpenShopUploadFileResourceModel::FILE_TYPE_IMG;
                $mappingData[$key]['position']     = UploadFileResourceEnum::SELECT_LOCATION_CASH_TYPE_MAPPING;
                $mappingData[$key]['updatedByUid'] = $rmsInfo->id;
            }
            UploadFileResourceService::insertData($mappingData);

            DB::commit();

            // 更新门店名称
//            ShopService::updateShopName($reqData['orderNo'], $reqData['shopName'] ?? '');

            event(new SignSiteMissionEvent($reqData['orderNo'], MissionTemplateEnum::STEP_STATUS_4, $rmsUid));
            event(new OpenShopProcessEvent($rmsUid, $mainProcessId, MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION,
                MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT));

            /*
            // 先不记录
            $orderLog = new OpenShopSignOrderLogModel();
            $orderLog->orderId = $orderModel->id;
            $orderLog->content = OpenShopSignOrderLogModel::TYPES[OpenShopSignOrderLogModel::SELECTION_SUBMIT_REPORT];
            $orderLog->type    = OpenShopSignOrderLogModel::SELECTION_SUBMIT_REPORT;
            $orderLog->operatorName    = $rmsInfo->username;
            $orderLog->createdByUid    = $rmsInfo->id;
            $orderLog->updatedByUid    = $rmsInfo->id;
            $orderLog->save();
            */
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ResponseHttpException(BaseErrorCode::$SHOP_LOCATION_ADD);
        }

    }

    const REPORT_PREFIX = 'kuafu_tiger_open_shop_report';

    public static function getReportInfo($orderNo)
    {
        $reportPathUrl = (string)OpenShopLocationModel::query()
                                                      ->where('orderNo', $orderNo)
                                                      ->value('shopLocationReportUrl');
        if (!mb_strlen($reportPathUrl)) {
            return [];
        }
        $urlMd5 = md5($reportPathUrl) . '.xlsx';
        self::prepareResource($urlMd5, $reportPathUrl);
        $reader      = new Xlsx();
        $spreadsheet = $reader->load(sys_get_temp_dir() . '/' . static::REPORT_PREFIX . '/' . $urlMd5);
        $data        = $spreadsheet
            ->getSheet(0)
            ->toArray();
        //目前规定只有两行 所以 count($data) = 2
        $info     = [];
        $dataTemp = $data[0] ?? [];
        foreach ($dataTemp as $k => $item) {
            if ($item == null) {
                break;
            }
            $info[] = [
                'title' => $item,
                'value' => $data[1][$k] ?: '-',
            ];
        }
        return $info;
    }

    /**
     * 固定的文件在本地的临时地址
     * @param $name
     * @return string
     */
    protected static function tempFileName($name): string
    {
        return sys_get_temp_dir() . '/' . self::REPORT_PREFIX . '/' . $name;
    }

    /**
     * 下载oss文件到本地
     * @param string $url
     * @param string $localPath
     */
    protected static function downloadFile(string $url, string $localPath)
    {
        @unlink($localPath);
        file_put_contents($localPath, file_get_contents(privateFilePath($url)));
    }

    protected static function prepareResource($fileName, $url)
    {
        if (!is_dir(sys_get_temp_dir() . '/' . static::REPORT_PREFIX)) {
            @unlink(sys_get_temp_dir() . '/' . static::REPORT_PREFIX);
            mkdir(sys_get_temp_dir() . '/' . static::REPORT_PREFIX, 0777, true);
        }
        if (!static::checkSha256($fileName, $url)) {
            static::downloadFile($url, static::tempFileName($fileName));
        }
    }

    /**
     * 检查文件指纹
     * @param $name
     * @param $url
     * @return bool
     */
    protected static function checkSha256($name, $url): bool
    {
        $tempFilename = static::tempFileName($name);
        if (!is_readable($tempFilename)) {
            return false;
        }
        $sha256 = substr(str_replace('/', '', $url), 0, 64);
        if ($sha256 != hash_file('sha256', $tempFilename)) {
            return false;
        }
        return true;
    }

    public static function addDisclosure($id, $files, $orderNo, $rmsInfo)
    {
        //根据orderNo获得shopCode
        $signOrder    = OpenShopSignOrderModel::query()
                                              ->where('orderNo', $orderNo)
                                              ->first();
        $shopCode     = (int)$signOrder->shopCode;
        $publicParams = [
            'type'         => ShopManualEnum::TYPE_DISCLOSURE,
            'shopCode'     => $shopCode,
            'weight'       => 6,
            'createdByUid' => $rmsInfo->id ?? 0,
            'updatedByUid' => $rmsInfo->id ?? 0,
            'orderNo'      => $orderNo,
            'createdAt'    => time(),
            'updatedAt'    => time(),
        ];
        $params       = [];
        $fileArr      = [];
        foreach ($files as $file) {
            $fileArr[] = getPrivateFileKey($file);
        }
        if ($id) {
            $oldDisclosure = [];
            OpenShopShopManual::query()
                              ->where('orderNo', $orderNo)
                              ->where('type', ShopManualEnum::TYPE_DISCLOSURE)
                              ->each(function ($item) use (&$oldDisclosure) {
                                  $oldDisclosure[] = $item->url;
                              });
//            $changesInfo = [
//                'old' => $oldDisclosure,
//                'new' => $fileArr,
//            ];
            //流程日志追加
//            $orderLog               = new OpenShopSignOrderLogModel();
//            $orderLog->orderId      = $signOrder->id;
//            $orderLog->content      = OpenShopSignOrderLogModel::TYPES[OpenShopSignOrderLogModel::UPDATED_SUBMIT_DISCLOSURE];
//            $orderLog->type         = OpenShopSignOrderLogModel::UPDATED_SUBMIT_DISCLOSURE;
//            $orderLog->operatorName = $rmsInfo->username;
//            $orderLog->createdByUid = $rmsInfo->id;
//            $orderLog->updatedByUid = $rmsInfo->id;
//            $orderLog->changes      = json_encode($changesInfo);
//            $orderLog->save();

            ChangeSupport::getInstance()->pushChanges([
                "theme"      => "修改披露单信息",
                "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_UPDATE,
                "data"       => [
                    [
                        "key"         => "url",
                        "beforeValue" => $oldDisclosure,
                        "afterValue"  => $fileArr,
                        "beforeText"  => $oldDisclosure,
                        "afterText"   => $fileArr,
                        "type"        => ChangeSupport::FILED_TYPE_PRIVATE_PICTURE,
                        "description" => "披露单文件地址"
                    ]
                ]
            ]);

            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                $signOrder->id,
                OpenShopSignOrderLogModel::UPDATED_SUBMIT_DISCLOSURE,
                $rmsInfo->username,
                $rmsInfo->id
            );

            OpenShopShopManual::query()
                              ->where("orderNo", $orderNo)
                              ->where("type", ShopManualEnum::TYPE_DISCLOSURE)
                              ->update([
                                  'isDeleted' => 1,
                              ]);
        } else {
            //修改披露单状态
            $orderModel                   = OpenShopSignOrderModel::firstOrNew([
                'orderNo' => $orderNo,
            ]);
            $orderModel->disclosureStatus = OpenShopSignOrderModel::DISCLOSURE_STATUS_ON;
            $orderModel->save();
            //流程日志追加
            ChangeSupport::getInstance()->buildInsertChanges(
                "上传披露单",
                ["url" => $fileArr],
                [
                    "url" => [
                        "type" => ChangeSupport::FILED_TYPE_PRIVATE_PICTURE,
                        "desc" => "披露单文件地址"
                    ]
                ]
            );

            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                $signOrder->id,
                OpenShopSignOrderLogModel::SELECTION_SUBMIT_DISCLOSURE,
                $rmsInfo->username,
                $rmsInfo->id
            );

//            $orderLog               = new OpenShopSignOrderLogModel();
//            $orderLog->orderId      = $signOrder->id;
//            $orderLog->content      = OpenShopSignOrderLogModel::TYPES[OpenShopSignOrderLogModel::SELECTION_SUBMIT_DISCLOSURE];
//            $orderLog->type         = OpenShopSignOrderLogModel::SELECTION_SUBMIT_DISCLOSURE;
//            $orderLog->operatorName = $rmsInfo->username;
//            $orderLog->createdByUid = $rmsInfo->id;
//            $orderLog->updatedByUid = $rmsInfo->id;
//            $orderLog->changes      = json_encode(['old' => [], 'new' => $fileArr]);
//            $orderLog->save();
            /*event(new OpenShopProcessEvent(
                $rmsInfo->id,
                $signOrder->mainProcessId,
                MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION,
                MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT
            ));*/
        }
        foreach ($fileArr as $item) {
            $params[] = array_merge($publicParams, ['url' => $item, 'name' => ShopManualEnum::TYPE_DISCLOSURE_NAME]);
        }
        OpenShopShopManual::insert($params);
    }

    public static function getInvestmentLocation(string $orderNo)
    {
        $openShopLocationModel = new OpenShopLocationModel();
        $investmentLocation    = $openShopLocationModel->getInvestmentLocation($orderNo);
        if (!empty($investmentLocation)) {
            //查询店铺信息
//            $shopCode                       = OpenShopSignOrderModel::query()
//                                                                    ->where('orderNo', $orderNo)
//                                                                    ->value('shopCode');
//            $shopName                       = SiteMissionService::getRmsShopNameByCode([$shopCode]);
            $investmentLocation['openTime'] = date('Y-m-d H:i:s', $investmentLocation['openTime']);
//            $investmentLocation['shopCode'] = $shopCode ?? '暂无店铺code';
//            $investmentLocation['shopName'] = $shopName['shopList'][0]['name'] ?? '暂无店铺名称';
            $fileRes                       = UploadFileResourceEnum::handleFileRes($investmentLocation['fileRel'],
                UploadFileResourceEnum::SELECT_LOCATION_DATABASE_LIST);
            $investmentLocation['fileRes'] = $fileRes;
        }
        return $investmentLocation;
    }

    public static function setReport($orderNo, $reqData, $rmsInfo, $mapping)
    {
        //查询是否有数据
        try {
            $locationModel = OpenShopLocationModel::query()
                                                  ->where('orderNo', $orderNo)
                                                  ->first();
            if (!$locationModel) {
                throw new ResponseHttpException(BaseErrorCode::$SHOP_LOCATION_NOT_EXISTS);
            }
            $rmsUid = ($rmsInfo->id) ?? 0;
            //根据orderNo获取主流程ID
            $orderModel    = OpenShopSignOrderModel::query()
                                                   ->where('orderNo', $orderNo)
                                                   ->first();
            $mainProcessId = $orderModel->mainProcessId;
            $originalData  = $locationModel->getRawOriginal();
            self::insertReport($reqData, $rmsUid, $mainProcessId, $locationModel);
            $nowData = $locationModel->getChanges();
            ChangeSupport::getInstance()->buildUpdateChanges(
                "修改选址信息",
                $originalData,
                collect($nowData)->except(["confirmStatus", "confirmTime"])->toArray(),
                OpenShopLocationModel::getOrderLogTranslate()
            );

            $mappingData = [];
            foreach ($mapping as $key => $value) {
                $mappingData[$key]['orderNo']      = $orderNo;
                $mappingData[$key]['url']          = getPrivateFileKey($value);
                $mappingData[$key]['createdAt']    = time();
                $mappingData[$key]['createdByUid'] = $rmsInfo->id;
                $mappingData[$key]['updatedAt']    = time();
                $mappingData[$key]['type']         = OpenShopUploadFileResourceModel::FILE_TYPE_IMG;
                $mappingData[$key]['position']     = UploadFileResourceEnum::SELECT_LOCATION_CASH_TYPE_MAPPING;
                $mappingData[$key]['updatedByUid'] = $rmsInfo->id;
            }
            UploadFileResourceService::updateFileListByPosition($orderNo,
                UploadFileResourceEnum::SELECT_LOCATION_LIST,
                $mappingData, OpenShopSignOrderLogModel::UPDATED_SUBMIT_DISCLOSURE);
            // 更新门店名称
//            ShopService::updateShopName($orderNo, $reqData['shopName'] ?? '');
            //写入订单日志
            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                OpenShopSignOrderModel::getOrderIdByOrderNo($orderNo),
                OpenShopSignOrderLogModel::UPDATE_SHOP_LOCATION,
                $rmsInfo->username,
                $rmsInfo->id,
            );
        } catch (\Exception $exception) {
            throw new ResponseHttpException(BaseErrorCode::$SHOP_LOCATION_ADD);
        }
    }

    public static function insertReport($reqData, $rmsUid, $mainProcessId, $locationModel, $step = 0)
    {
        $addressSelect                    = $reqData['addressSelect'];
        $reportUrl                        = empty($reqData['reportUrl']) ? "" : getPrivateFileKey($reqData['reportUrl']);
        $locationModel->mainProcessId     = $mainProcessId;
        $locationModel->shopAddressPrefix = $reqData['addressPrefix'];
        $locationModel->provinceCode      = $addressSelect[0] ?? 0;
        $locationModel->cityCode          = $addressSelect[1] ?? 0;
        $locationModel->districtCode      = $addressSelect[2] ?? 0;
        $locationModel->shopDetailAddress = $reqData['shopDetailAddress'];
        $locationModel->shopRent          = $reqData['shopRent'];
        if ($step > 0) {
            $locationModel->step = $step;
        }
        $locationModel->shopArea               = $reqData['shopArea'];
        $locationModel->rentPer                = $reqData['rentPer'] ?? 0;
        $locationModel->monthlyRent            = $reqData['monthlyRent'] ?? 0;
        $locationModel->shopType               = $reqData['shopType'];
        $locationModel->shopScopeProducts      = $reqData['shopScopeProducts'];
        $locationModel->shopLocationReportUrl  = $reportUrl;
        $locationModel->cashType               = $reqData['cashType'];
        $locationModel->openTime               = $reqData['openTime'];
        $locationModel->electricQuantity       = $reqData['electricQuantity'];
        $locationModel->isAddElectricNum       = $reqData['isAddElectricNum'];
        $locationModel->smokeNumber            = $reqData['smokeNumber'];
        $locationModel->isReformSmoke          = $reqData['isReformSmoke'];
        $locationModel->upperWaterDiameter     = $reqData['upperWaterDiameter'] ?? 0;
        $locationModel->lowerWaterDiameter     = $reqData['lowerWaterDiameter'] ?? 0;
        $locationModel->isReformWater          = $reqData['isReformWater'];
        $locationModel->shopLocationReportLink = $reqData['shopLocationReportLink'] ?? '';
        $locationModel->submitReportTime       = time();
        $locationModel->confirmStatus          = OpenShopLocationModel::SUBMIT_REPORT_STATUS_OFF;
        $locationModel->confirmTime            = 0;
        $locationModel->updatedByUid           = $rmsUid;
        $locationModel->locationType           = $reqData['locationType'];
        $locationModel->depositMonth           = $reqData['depositMonth'] ?? 0;
        $locationModel->payMonth               = $reqData['payMonth'] ?? 0;
        $locationModel->isLocationSelf         = $reqData['isLocationSelf'];
        $locationModel->averageDaily           = $reqData['averageDaily'];
        $locationModel->averageDailyBreak      = $reqData['averageDailyBreak'];
        $locationModel->save();
    }

    public static function getImgList($orderNo)
    {
        $position = UploadFileResourceEnum::SELECT_LOCATION_LIST;
        $fileList = UploadFileResourceService::getFileListByPosition($orderNo, $position);
        if (empty($fileList->toArray())) {
            return null;
        } else {
            return UploadFileResourceEnum::handleFileRes($fileList,
                UploadFileResourceEnum::SELECT_LOCATION_DATABASE_LIST);
        }
    }

}
